#include"comm.hpp"

int main()
{
    key_t key = ftok(PATH_NAME,PROJ_ID);
    if(key==-1)
    {
        perror("ftok");
        exit(1);
    }
    Log("create key done", Debug) << " client key : " << key << endl;
    //sleep(5);

    int shmid = shmget(key,sizeof(SHM_SIZE),IPC_CREAT);

    if(shmid < 0)
    {
        Log("create shm failed", Error) << " client key : " << key << endl;
        exit(2);
    }
    Log("create shm success", Error) << " client key : " << key << endl;
    //sleep(5);

    char* shmaddr = (char*)shmat(shmid,nullptr,0);
    if(shmaddr == nullptr)
    {
        Log("attach shm failed", Error) << " client key : " << key << endl;
        exit(3);
    }
    Log("attach shm success", Error) << " client key : " << key << endl;
    //sleep(5);

    int fd = OpenFifo(FIFO_NAME,O_WRONLY);
    //使用
    while(true)
    {
        ssize_t s = read(0,shmaddr,SHM_SIZE-1);
        if(s>0)
        {
            shmaddr[s-1]=0;
            Signal(fd);
            if(strcmp(shmaddr,"quit")==0) break;
        }
    }
    // char a = 'a';
    // for(;a<='d';a++)
    // {
    //     snprintf(shmaddr,SHM_SIZE,"hello server,我是其他进程,我的pid: %d, inc: %c\n",getpid(),a);
    //     sleep(2);
    // }
    // strcpy(shmaddr,"quit");
    // 去关联

    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("detach shm success", Error) << " client key : " << key << endl;
    //sleep(5);
    CloseFifo(fd);
    return 0;
}